//
//  FGAppDelegate.m
//  Mi6App
//
//  Created by Mr.Lemon on 7/25/13.
//  Copyright (c) 2013 4G Secure. All rights reserved.
//

#import "FGAppDelegate.h"
#import "FGListVoucherController.h"
#import "FGHomeViewController.h"
#import "DefaultSHKConfigurator.h"
#import "SHKConfiguration.h"
#import "SHKFacebook.h"
#import "FGListVoucherController.h"
#import "FGNewVoucherViewController.h"


@implementation FGAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
//    FGListVoucherController *view = [[FGListVoucherController alloc] initWithNibName:@"FGListVoucherController" bundle:nil];
    
    FGNewVoucherViewController *view = [[FGNewVoucherViewController alloc] initWithNibName:@"FGNewVoucherViewController" bundle:nil];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:view];
    
    [self registerPushWithAppleServer];
    
    //Init faecbook share config
    
    DefaultSHKConfigurator *configurator = [[DefaultSHKConfigurator alloc] init];
    [SHKConfiguration sharedInstanceWithConfigurator:configurator];
    
    [nav setNavigationBarHidden:YES animated:NO];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    return YES;
}

-(void)registerPushWithAppleServer
{
    NSString *UUID = [[NSUserDefaults standardUserDefaults] objectForKey:@"ApplicationUUIDKey"];
    if (!UUID) {
        CFUUIDRef uuid = CFUUIDCreate(NULL);
        UUID = (NSString *)CFBridgingRelease(CFUUIDCreateString(NULL, uuid));
        CFRelease(uuid);
        [[NSUserDefaults standardUserDefaults] setObject:UUID forKey:@"ApplicationUUIDKey"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];

}

#pragma mark - Rotate
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    NSUInteger orientations = UIInterfaceOrientationMaskPortrait;
    
    if (self.window.rootViewController) {
        NSLog(@"%@",[(UINavigationController *)self.window.rootViewController viewControllers]);

        NSArray *arrController = [(UINavigationController *)self.window.rootViewController viewControllers];
        for (UIViewController *controller in arrController){
            if ([controller isKindOfClass:[FGListVoucherController class]]) {
                orientations = UIInterfaceOrientationMaskAll;
            }
        }
    }
    return orientations;
}

//For authen facebook
- (BOOL)handleOpenURL:(NSURL*)url
{
    
    NSString* scheme = [url scheme];
    if ([scheme hasPrefix:[NSString stringWithFormat:@"fb%@", SHKCONFIG(facebookAppId)]])
        return [SHKFacebook handleOpenURL:url];
    return YES;
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return [self handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application
      handleOpenURL:(NSURL *)url
{
    return [self handleOpenURL:url];
}

//End for authen facebook

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark PUSH NOTIFICATION
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    // getting an NSString
    NSString *uuid = [prefs stringForKey:@"ApplicationUUIDKey"];
    
    NSString *str =  [NSString stringWithFormat:@"%@",deviceToken];
    
    str = [str stringByReplacingOccurrencesOfString:@"<"
                                         withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@" "
                                         withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@">"
                                         withString:@""];
    
    NSString *datastr = [NSString stringWithFormat:@"{\"service\":\"UNIQUSH_SERVICE\",\"subscriber\": \"%@\",\"pushservicetype\" : \"apns\",\"devtoken\" : \"%@\"}",uuid , str];
    
    NSData* data = [datastr dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@", data);
    NSURL *url = [NSURL URLWithString:@"http://12345678:vX16moq_912Bz@54.229.82.188:8080/rest-api/subscribe"];
    
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [data length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: data];
    NSLog(@"request auth working: %@", request);
    NSLog(@"request headers : %@", [request allHTTPHeaderFields]);
    NSLog(@"request body : %@", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    // getting an NSString
    NSString *uuid = [prefs stringForKey:@"ApplicationUUIDKey"];
    
    NSString *str =  [NSString stringWithFormat:@"%@",@"0000"];
    
    NSString *datastr = [NSString stringWithFormat:@"{\"service\":\"UNIQUSH_SERVICE\",\"subscriber\": \"%@\",\"pushservicetype\" : \"apns\",\"devtoken\" : \"%@\"}",uuid, str];
    
    NSData* data = [datastr dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@", data);
    NSURL *url = [NSURL URLWithString:@"http://12345678:vX16moq_912Bz@54.229.82.188:8080/rest-api/subscribe"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [data length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: data];
    NSLog(@"request : %@", request);
    NSLog(@"request headers : %@", [request allHTTPHeaderFields]);
    NSLog(@"request body : %@", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
    
    [NSURLConnection connectionWithRequest:request delegate:self];
}



- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"%@",userInfo);
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@",response);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSDictionary *result;
    NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"Authentication --- %@",response);
    
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"get data fail");
}

@end
